import axios from 'axios'
import store from '../store'
// 创建axios实例
const service = axios.create({
  baseURL: 'http://127.0.0.1:8888/api/private/v1/',
  timeout: 5000// 请求超时时间
})
// 请求拦截器
service.interceptors.request.use(
  config => {
    axios.defaults.headers.Authorization = window.sessionStorage.getItem('token')
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  config => {
    return config
  },
  error => {
    // 请求错误则向sotre commit状态变化
    const httpError = {
      hasError: true,
      status: error.response.status,
      statusText: error.response.statusText
    }
    store.commit('ON_HTTP_ERROR', httpError)

    return Promise.reject(error)
  }
)

export default service
